<template>
  <div class="contain">
    <el-tabs v-model="activeName">
      <el-tab-pane label="当前推荐上样清单" name="first">
        <div class="item">
          <search-form
            ref="refSearch"
            :label-width="150"
            :search-config="[]"
            @clear="handleClear"
            @search="handleSearch"
          >
            <div style="width:50%" class="qup-search-item">
              <el-form-item label="推荐上样门店:" size="mini" prop="shopCode">
                <el-select
                  placeholder="请选择"
                  :value="shopData"
                  value-key="shopCode"
                  @change="changeShop"
                >
                  <el-option
                    v-for="item in shopList"
                    :key="item.shopName"
                    :label="item.shopName"
                    :value="item"
                  />
                </el-select>
              </el-form-item>
            </div>
            <div class="qup-search-item">
              <el-form-item label="推荐上样规则:" size="mini" prop="sampleType">
                <template #label>
                  <!-- 推荐上样规则说明 -->
                  <el-popover
                    style="width:30%"
                    placement="bottom"
                    title="提示信息"
                    trigger="hover"
                  >
                    <div>
                      <el-image fit="contain" :src="PIC" />
                    </div>
                    <div slot="reference"><i style="font-size:14px;padding-right:4px" class="el-icon-question" />推荐上样规则:</div>

                    <!-- <el-button slot="reference" type="text" size="mini">推荐上样规则</el-button> -->
                  </el-popover>
                  <!-- <el-popover
                    style="width:30%"
                    placement="bottom"
                    title="说明"
                    trigger="hover"
                  >
                    <div>
                      一、选择的“推荐上样规则”不同，推荐上样的产品可能就不同。<br>
                      1、上样时间:<br>
                      以门店销售数据为基础，优先选择最近上市的产品进行推荐 <br>
                      2、区域销量: <br>
                      以门店销售数据为基础，优先选择办事处要货排名靠前的产品进行推荐 <br>
                      3、门店销量: <br>
                      以门店销售数据为基础，优先选择该门店销售排名靠前的产品进行推荐 <br>
                      二、数据更新时间规则: <br>
                      当天创建更新的数据，在当日不参与计算，只能看到截止到前一天的上样推荐。
                    </div>
                    <div slot="reference"><i style="font-size:14px;padding-right:4px" class="el-icon-question" />推荐上样规则:</div>
                  </el-popover> -->
                </template>
                <el-radio-group v-model="formData.sampleType">
                  <el-radio v-for="item in sortTypeList" :key="item.dictCode" :label="item.dictCode">{{ item.dictName }}</el-radio>
                </el-radio-group>
              </el-form-item>
            </div>
            <div v-loading="dataLoading" class="qup-search-item">
              <el-form-item label="专区:" size="mini" prop="displayAreaCode">
                <el-radio-group v-model="formData.displayAreaCode" @change="changeDisplayArea(formData.displayAreaCode)">
                  <el-radio
                    v-for="item in displayAreaList"
                    :key="item.displayAreaCode"
                    :label="item.displayAreaCode"
                  >{{ item.displayAreaName +item.displayAreaCode }}</el-radio>
                </el-radio-group>
              </el-form-item>
            </div>
            <div class="qup-search-item">
              <el-form-item label="推荐数量:" size="mini" prop="totalNum">
                <el-radio-group v-model="formData.totalNum">
                  <el-radio v-for="item in totalNumList" :key="item.name" :label="item.name">{{ item.name+(item.code?('('+item.code+'套)'):'' ) }}</el-radio>
                </el-radio-group>
                <el-button size="mini" type="text" @click="handleDetail(activeArea)">常规款分布</el-button>
              </el-form-item>
            </div>
            <div class="qup-search-item">
              <el-form-item label="尺寸区间:" size="mini" prop="productSize">
                <el-select
                  v-model="formData.productSize"
                  clearable
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in productSizeList"
                    :key="item.showValue"
                    :label="item.showValue"
                    :value="item.showValue"
                  />
                </el-select>
              </el-form-item>
            </div>
            <div class="qup-search-item">
              <el-form-item label="价格区间:" size="mini" prop="price">
                <el-select
                  v-model="formData.price"
                  clearable
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in priceList"
                    :key="item.showValue"
                    :label="item.showValue"
                    :value="item.showValue"
                  />
                </el-select>
              </el-form-item>
            </div>
            <div class="qup-search-item">
              <el-form-item label="型号:" size="mini" prop="modelNumber">
                <el-input v-model="formData.modelNumber" size="mini" />
              </el-form-item>
            </div>
            <div style="width:70%" class="qup-search-item">
              <el-form-item label="排序:" size="mini" prop="sortSampleType">
                <el-radio-group v-model="formData.sortSampleType">
                  <el-radio v-for="item in sortTypeList" :key="item.dictCode" :label="item.dictCode">{{ item.dictName }}</el-radio>
                </el-radio-group>
              </el-form-item>
            </div>
          </search-form>
          <div class="item">
            <table-box
              ref="refTable"
              table-size="mini"
              :table-config="tableConfig"
              show-index
              :other-raw="params"
              no-request
              :table-height="400"
              :show-custom-setting="false"
              :other-filters="otherFilter"
              @data-change="changeTableData"
              @btnOperate="btnOperate"
            >
              <el-table-column fixed="right" min-width="80" label="操作">
                <template slot-scope="scope">
                  <el-button v-if="scope.row.isChecked" size="mini" type="text" @click.native="handleChange(scope.row)">替换</el-button>
                </template>
              </el-table-column>
            </table-box>
          </div>
          <el-dialog
            :title="activeCode"
            :visible.sync="dialogVisible"
            width="700px"
          >
            <detail-table v-if="dialogVisible" :convention-num="activeNumber" :shop-code="shopData.shopCode" :code="activeCode" />
            <span slot="footer" class="dialog-footer">
              <el-button @click="dialogVisible = false">关 闭</el-button>
            </span>
          </el-dialog>
          <select-form
            v-if="showSelectDlg"
            :relation-data="activeData"
            :params="params"
            :visible.sync="showSelectDlg"
            :other-filters2="otherFilter"
            @success="refreshTable"
          />
        </div>
      </el-tab-pane>
      <el-tab-pane label="已保存的上样清单" name="second">
        <saved-list ref="saveList" />
      </el-tab-pane>
    </el-tabs>

    <!-- 图片预览 -->
    <el-image-viewer
      v-if="imgDialogVisible"
      :on-close="handleCloseImg"
      :url-list="previewImgs"
    />
  </div>
</template>
<script>
import PIC from '@/assets/info.png'
import { formaterData } from '@/utils'
import ElImageViewer from 'element-ui/packages/image/src/image-viewer'
import { getShopList } from '@/api/display/salesData'
import { queryMainData, saveRecommend } from '@/api/display/recommend'
import { getSpaceList } from '@/api/display/space'
import { getDictByPatchType } from '@/api/dataDict'
import { getChildTableList } from '@/api/display/areaMatain'
import selectForm from './selectForm'
import detailTable from './detailTable'
import savedList from './SavedList.vue'
export default {
  name: 'Recommend',
  components: { selectForm, detailTable, ElImageViewer, savedList },
  data() {
    const that = this
    return {
      PIC,
      saveLoading: false,
      activeName: 'first',
      imgDialogVisible: false,
      tableData: [],
      previewImgs: [],
      activeArea: {}, // 当前选中专区的套数
      formData: {
        shopCode: '',
        shopName: '',
        sampleType: 'A',
        displayAreaName: '',
        totalNum: '全部',
        productSize: '',
        price: '',
        modelNumber: '',
        sortSampleType: 'A'
      },
      displayAreaList: [],
      productSizeList: [],
      displayAreaCategoryList: [],
      priceList: [],
      totalNumList: [],
      dataLoading: false,
      shopData: { shopCode: '', shopName: '' },
      shopList: [], // { shopCode: 'K100176701', sampleType: '测试门店' }
      showSelectDlg: false,
      otherFilter: [],
      totalNumber: '-',
      activeFilter: { shopCode: '', sampleType: 'A' },
      params: {},
      activeCode: '',
      activeNumber: 0,
      dialogVisible: false,
      activeData: {},
      sortTypeList: [],
      tableConfig: {
        interfacePath: `${process.env.VUE_APP_BASE_API}/api/v1/displaySalesRanking/page`,
        buttonGroupCode: 'default',
        hideSearchBar: true,
        tabIndex: 1,
        pageSize: 10,
        pageFlag: false,
        // order: 'asc',
        // sort: 'isChecked',
        // 表格字段动态配置
        setting: [
          {
            prop: 'pic',
            label: '产品主图',
            minWidth: '80',
            render: (h, data, row) => {
              const DomArr = [
                <div style='display:flex'>
                  <img
                    onClick={that.handlePreview.bind(this, data)}
                    src={'https://gcenterimg.quanyou.com.cn/' + data.pic}
                    height='50'
                    width='50'
                  >
                  </img>
                </div>
              ]
              return DomArr
            }
          },
          {
            prop: 'productName',
            label: '产品名称',
            minWidth: '160'
          },
          {
            prop: 'productLocation',
            label: '产品定位',
            minWidth: '90'
          },
          {
            prop: 'modelNumber',
            label: '型号',
            minWidth: '90'
          },
          {
            prop: 'marketTime',
            label: '上市时间',
            minWidth: '100'
          },
          {
            prop: 'productSize',
            label: '尺寸',
            minWidth: '90'
          },
          {
            prop: 'price',
            label: '价格',
            minWidth: '90'
          }
        ],
        btnList: [{
          buttonName: '保存上样推荐清单',
          outerFlag: true,
          optCode: 'save'
        }
        // {
        //   buttonName: '刷新上样推荐清单',
        //   outerFlag: true,
        //   optCode: 'refresh'
        // }
        ]
      },
      visible: false
    }
  },
  mounted() {
    this.$refs.refSearch.toggleMore()
  },
  async created() {
    getShopList().then(res => {
      if (res.success && res.data.length > 0) {
        this.shopList = res.data
        this.changeShop(this.shopList[0])
      } else {
        this.$message.warning('当前用户下没有门店')
      }
    }).catch(() => {
    })
    getSpaceList().then(res => {
      this.displayAreaCategoryList = res.data || []
    })
    const { SAMPLE_TYPE } = await getDictByPatchType(['SAMPLE_TYPE'])
    this.sortTypeList = SAMPLE_TYPE // 排序方式
  },
  methods: {
    // 关闭图片预览
    handleCloseImg() {
      this.imgDialogVisible = false
    },
    handlePreview(data) {
      this.previewImgs = ['https://gcenterimg.quanyou.com.cn/' + data.pic]
      this.imgDialogVisible = true
    },
    handleSearch() {
      console.log(this.formData)
      const filtersRaw = [{ 'id': 'shopCode', 'property': 'shopCode', 'operator': '=', 'value': this.formData.shopCode },
        { 'id': 'displayAreaCode', 'property': 'displayAreaCode', 'operator': '=', 'value': this.formData.displayAreaCode },
        { 'id': 'sampleType', 'property': 'sampleType', 'operator': '=', 'value': this.formData.sampleType }
      ]
      if (this.formData.price) filtersRaw.push({ 'id': 'price', 'property': 'price', 'operator': '=', 'value': this.formData.price })
      if (this.formData.productSize) filtersRaw.push({ 'id': 'productSize', 'property': 'productSize', 'operator': '=', 'value': this.formData.productSize })
      if (this.formData.modelNumber) filtersRaw.push({ 'id': 'modelNumber', 'property': 'modelNumber', 'operator': 'like', 'value': this.formData.modelNumber })
      if (this.formData.totalNum && this.formData.totalNum !== '全部') filtersRaw.push({ 'id': 'productLocation', 'property': 'productLocation', 'operator': '=', 'value': this.formData.totalNum })
      const { totalNum, conventionNum, imageNum, promotionNum, sortSampleType = this.formData.sortSampleType } = this.activeArea
      const paramsRaw = { totalNum, conventionNum, imageNum, promotionNum, sortSampleType }
      this.otherFilter = filtersRaw
      this.params = paramsRaw
      this.refreshTable()
      console.log(filtersRaw, paramsRaw)
    },
    changeDisplayArea(data) {
      if (!data) return
      // 专区改变时 改变推荐数量选值
      const temp1 = this.displayAreaList.filter(v => v.displayAreaCode === data)
      if (temp1.length) this.activeArea = temp1[0]
      this.totalNumList = [{ name: '全部', code: this.activeArea.totalNum }, { name: '形象款', code: this.activeArea.imageNum },
        { name: `常规款`, code: this.activeArea.conventionNum }, { name: '促销款', code: this.activeArea.promotionNum }]
      this.formData.totalNum = '全部'

      const temp = this.displayAreaCategoryList.filter(v => v.areaCode === data)
      if (temp.length > 0) {
        getChildTableList(temp[0].sizeIntervalCode).then(res => {
          this.productSizeList = res.data.records
          this.formData.productSize = ''
        })
        getChildTableList(temp[0].priceIntervalCode).then(res => {
          this.priceList = res.data.records
          this.formData.price = ''
        })
      }
    },
    // 按钮组
    btnOperate(flag) {
      switch (flag) {
        case 'save':
          this.handleSave()
          break
        case 'refresh':
          this.refreshTable()
          break
        default:
          break
      }
    },
    // 保存上样清单
    // `专区【${this.formData.displayAreaCode}】，门店：【${this.formData.shopName}】，推荐上样规则：【${this.formData.sampleType}】。是否保存?`,
    handleSave() {
      if (this.saveLoading) return
      if (!this.formData.shopCode || !this.formData.displayAreaCode || !this.formData.sampleType) return
      const h = this.$createElement
      this.$msgbox({
        title: '保存此条件上样清单',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        showCancelButton: true,
        message: h('p', null, [
          h('div', null, `专区：【${formaterData(this.displayAreaList, this.formData.displayAreaCode, 'displayAreaName', 'displayAreaCode')}】`),
          h('div', null, `门店：【${this.formData.shopName}】`),
          h('div', null, `推荐上样规则：【${formaterData(this.sortTypeList, this.formData.sampleType)}】`),
          h('div', { style: 'color: #E6A23C' }, `确认保存？`)
        ]),
        type: 'warning'
      }).then(() => {
        const item = {
          displayAreaCode: this.formData.displayAreaCode,
          sampleType: this.formData.sampleType,
          shopCode: this.formData.shopCode
        }
        this.saveLoading = true
        saveRecommend(item).then(res => {
          if (res.success) {
            this.$message.success('保存成功')
            this.$ref.saveList.refreshTable()
          }
          this.saveLoading = false
        }).catch(() => {
          this.saveLoading = false
        })
      }).catch(() => {
        this.saveLoading = false
      })
    },
    changeShop(data) {
      this.shopData = { shopName: data.shopName || '', shopCode: data.shopCode }
      this.formData.shopCode = data.shopCode
      this.formData.shopName = data.shopName
      const otherFilters1 = [{ 'id': 'shopCode', 'property': 'shopCode', 'operator': '=', 'value': data.shopCode }]
      this.activeFilter.shopCode = data.shopCode
      if (this.shopList.length === 0) {
        this.$message.warning('当前用户下没有门店')
        return
      }
      this.dataLoading = true
      queryMainData(otherFilters1).then(res => {
        if (res.success && res.data.records.length > 0) {
          this.displayAreaList = res.data.records
          this.activeArea = this.displayAreaList[0]
          this.formData.displayAreaCode = this.displayAreaList[0].displayAreaCode
          this.totalNumList = [{ name: '全部', code: this.displayAreaList[0].totalNum }, { name: '形象款', code: this.displayAreaList[0].imageNum },
            { name: `常规款`, code: this.displayAreaList[0].conventionNum }, { name: '促销款', code: this.displayAreaList[0].promotionNum }]
          this.formData.totalNum = '全部'
          this.changeDisplayArea(this.displayAreaList[0].displayAreaCode)
        } else {
          this.displayAreaList = []
          this.activeArea = {}
          this.formData.displayAreaCode = ''
          this.totalNumList = []
          this.formData.totalNum = ''
          this.changeDisplayArea('')
        }
        this.dataLoading = false
      }).catch(() => {
        this.dataLoading = false
      })
    },
    // 替换
    handleChange(data) {
      this.activeData = data
      this.showSelectDlg = true
    },
    handleDetail(data) {
      if (!data.displayAreaCode) return
      this.activeCode = data.displayAreaCode
      this.activeNumber = data.conventionNum
      this.dialogVisible = true
    },
    resetTableHeight() {
      this.$refs.refTable.setTableHeight()
    },
    refreshTable() {
      if (this.shopList.length === 0) {
        this.$message.warning('当前用户下没有门店')
        return
      }
      this.$nextTick(() => {
        this.$refs.refTable.initTableData()
      })
    },
    handleClear() {
      this.formData.price = ''
      this.formData.productSize = ''
      this.formData.modelNumber = ''
    },
    changeTableData(res) {
      console.log('数据', res.data.records)
      this.tableData = res.data.records
    }
  }
}
</script>
<style lang="scss" scoped>
/deep/.table-handelclick-text {
  color: #3DC094;
  cursor: pointer;
}
/deep/.el-radio__input {
    display: none;
    cursor: pointer;
    vertical-align: middle;
}
/deep/.qup-search-form .qup-search-item .el-radio-group .el-radio {
    border: 1px solid #3dc094;
    padding-right: 5px;
    border-radius: 3px;
    line-height: 28px;
}
/deep/.qup-search-form .qup-search-item .el-radio__input.is-checked+.el-radio__label {
    color: #fff;
}
/deep/label.el-radio.is-checked {
    background-color: #3dc094;
    color: #fff
}

</style>
